package cn.david.order.service.impl;


import cn.david.basic.service.impl.BasicServiceImpl;
import cn.david.basic.util.CodeGenerateUtils;
import cn.david.basic.util.PageList;
import cn.david.order.domain.AdoptOrder;
import cn.david.order.domain.OrderAddress;
import cn.david.order.mapper.AdoptOrderMapper;
import cn.david.order.mapper.OrderAddressMapper;
import cn.david.order.query.AdoptOrderQuery;
import cn.david.order.service.IAdoptOrderService;
import cn.david.org.domain.Employee;
import cn.david.org.mapper.EmployeeMapper;
import cn.david.pay.constants.OrderConstants;
import cn.david.pay.domain.PayBill;
import cn.david.pay.mapper.PayBillMapper;
import cn.david.pay.service.IPayBillService;
import cn.david.pet.domain.Pet;
import cn.david.pet.mapper.PetMapper;
import cn.david.quartz.config.QuartzConfig;
import cn.david.quartz.constants.QuartzConstants;
import cn.david.quartz.service.IQuartzService;
import cn.david.quartz.utils.QuartzJobInfo;
import cn.david.quartz.utils.QuartzUtils;
import cn.david.user.domian.Logininfo;
import cn.david.user.domian.User;
import cn.david.user.domian.UserAddress;
import cn.david.user.mapper.UserAddressMapper;
import cn.david.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BasicServiceImpl<AdoptOrder> implements IAdoptOrderService {
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService billService;
    @Autowired
    private IQuartzService quartzService;
    @Override
    public String submit(Map<String, Object> params, Logininfo loginInfo) {
        //把字符串转成LONG类型
        Long petId = Long.valueOf(params.get("pet_id").toString());
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());
        //修改宠物下架
        Pet pet = petMapper.loadById(petId);
        User user = userMapper.loadByLogininfoId(loginInfo.getId());
        if (pet != null) {
            pet.setState(0);
            pet.setOffsaletime(new Date());
            //绑定属性

            pet.setUser_id(user.getId());
            petMapper.update(pet);
        }
        //生成订单
        AdoptOrder order = initAdoptOrder(petId, user, pet);
        String unionPaSn =CodeGenerateUtils.generateUnionPaySn();
        order.setPaySn(unionPaSn);
        adoptOrderMapper.save(order);
        //订单地址
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);
        orderAddressMapper.save(orderAddress);
        //支付
        PayBill bill = initPayBill(payMethod, pet, user, order);
        payBillMapper.save(bill);

        //生成支付订单
        //调用接口
        //定时取消
        QuartzJobInfo info = new QuartzJobInfo();
        info.setType(QuartzConstants.ORDER_ADOPT_TYPE_CANCEL);
        String jobName = QuartzConstants.ORDER_PRODUCT_CANCEL_PREFIX + order.getPaySn();
        info.setJobName(jobName);
        HashMap<String, Object> paramsQuartz = new HashMap<>();
        paramsQuartz.put("orderId", order.getId());
        info.setParams(paramsQuartz);
        info.setFireDate(order.getLastPayTime());
        //添加超时未支付取消定时任务
        quartzService.addJob(info);
        System.out.println(order.getDigest()+"添加定时任务成功");
        return billService.pay(bill);
        //返回同步消息
        //@TODO 定时器

    }

    private PayBill initPayBill(Long payMethod, Pet pet, User user, AdoptOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest(order.getDigest());
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setLastPayTime(new Date(System.currentTimeMillis()+ OrderConstants.ORDER_TIMEOUT));
        bill.setPayChannel(payMethod);
        bill.setBusinessType(OrderConstants.BUSINESS_TYPE_ADOPT_ORDER);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(user.getId());
        bill.setNickName(user.getUsername());
        bill.setShop_id(pet.getShop_id());
        return bill;
    }

    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, Long id) {
        Employee employee = employeeMapper.loadByLoginInfoId(id);
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());

        }
        return super.queryData(query);
    }

    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, Long id) {
        User user = userMapper.loadByLogininfoId(id);
        if (user!=null){
            query.setUserId(user.getId());
        }
        return super.queryData(query);
    }

    @Override
    public void quartzCancel(Long orderId) {
        //定时任务修改领养订单订单
        AdoptOrder order = adoptOrderMapper.loadById(orderId);
        order.setState(-1);
        adoptOrderMapper.update(order);
        //修改支付订单
        String paySn = order.getPaySn();
        PayBill bill = payBillMapper.loadByUnionPaySn(paySn);
        bill.setState(-1);
        payBillMapper.update(bill);
        System.out.println(order.getDigest()+"取消订单了");


    }

    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setId(null);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Long petId, User user, Pet pet) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[陶大大摘要]" + pet.getName() + "领养订单");
        order.setPrice(pet.getSaleprice());
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        order.setLastPayTime(new Date(System.currentTimeMillis() + 15 * 60 * 1000));
        order.setPet_id(petId);
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        return order;
    }
}
